# -*- coding: utf-8 -*-
""" 
@author: catherine wei
@contact: catherine@oddmeta.com
@software: PyCharm
@file: odd_log.py
@info: 消息模版
"""

import logging
import os  # 新增：导入os模块用于目录操作
from logging import handlers
import platform
import odd_asr_config as config


def _logging():
    FORMAT = "%(asctime)s %(levelname)s %(filename)s:%(lineno)s (%(process)s-%(thread)s) - %(message)s "
    DATE = '%Y-%m-%d %H:%M:%S'

    format = logging.Formatter(FORMAT, DATE)
    logfile = config.log_path + config.log_file

    # 新增：确保日志目录存在
    log_dir = os.path.dirname(logfile)
    if not os.path.exists(log_dir):
        os.makedirs(log_dir, exist_ok=True)  # exist_ok=True 防止目录已存在时出错

    log = logging.getLogger(logfile)

    # 避免重复添加处理器
    if log.handlers:
        return log

    th = handlers.TimedRotatingFileHandler(
        filename=logfile,
        when='MIDNIGHT',
        backupCount=10,
        encoding='utf-8'
    )
    th.setFormatter(format)
    log.addHandler(th)

    stdout = logging.StreamHandler()
    stdout.setFormatter(format)
    log.addHandler(stdout)

    if config.Debug:
        enableProtoPrint = False
        if enableProtoPrint:
            logging.basicConfig(level=logging.DEBUG, format=FORMAT, datefmt=DATE)
        else:
            ch = logging.StreamHandler()
            ch.setFormatter(format)
            log.addHandler(ch)

    log.setLevel(config.log_level)

    return log


logger = _logging()